
const mysql = require('mysql');
const bodyParser = require('body-parser')

const connect = mysql.createPool({
  port: 3306,
  host: '47.101.45.245',
  user: '1809a-commuity',
  database: '1809a-commuity',
  password: 'ZktM5BAHx8jzzJtJ'
})

const exec = (sql, params) => {
  return new Promise((resolve, reject) => {
    connect.query(sql, params, (err, data) => {
      if (err) reject(err);
      resolve(data)
    })
  })
}

// npm start
// npm run start
// vue create  bin: {  }
// scripts: {} npm命令
// npm run
/// npm start
module.exports = function (app) {
  app.use(bodyParser())
  // app.use(bodyParser())
  app.get('/api/test', async (req, res) => {
    const data = await exec(`select * from goods`)
    res.send({
      code: 0,
      msg: 'success',
      data
    })
  })

  app.post('/api/update', async (req, res) => {
    const { price, skuCount, imgUrl, id } = req.body;
    const insertData = await exec(`UPDATE goods
    SET skuCount = ?, price = ?, imgUrl = ? WHERE id = ?`,
    [skuCount, price, imgUrl, id]
    )
    res.send({
      code: 0,
      msg: 'success',
      data: insertData
    })
  })

  // 删除
  app.get('/api/delete', async (req, res) => {
    const { id } = req.query;
    // api/delete?id=1,2,3,4,5  split.join(',')
    // delete from goods where id = (1,2,3,4,5);
    const deleteData = await exec(`delete from goods where id in (?)`, [id])
    res.send({
      code: 0,
      msg: 'success',
      data: deleteData
    })
  })
  // 添加
  app.post('/api/add', async (req, res) => {
    const { price, skuCount, imgUrl } = req.body;
    const addData = await exec(`insert into goods (price, skuCount, imgUrl) values (?, ?, ?)`, [price, skuCount, imgUrl])
    res.send({
      code: 0,
      msg: 'success',
      data: addData
    })
  })

};


//   app.get('/api/test', (req:any, res:any) => {
//     res.json({
//       code: 0,
//       msg: 'success'
//     })
//   })
// }
